#include <protocols/smtp/SMTP.hpp>

SMTP::SMTP()
{
  sender = "";
  mail_host = "";
  response = "";
  /* Currently not used. Technically, we shouldn't
     do an RCPT TO without doing a MAIL FROM. This
     var is to check against that. Also, the user
     shouldn't call for an RCPT after starting to
     send data. But, again, we can get all neces-
     sary data from the user and re-order and send
     them all at once.
  */
  rcpt_allowed = true;
}

SMTP::SMTP(string host_ip)
{
  sender = "";
  mail_host = host_ip;
  response = "";
  rcpt_allowed = true;
  conn.connect_to(host_ip, 25, 4);
}

SMTP::~SMTP()
{
  /* Send SMTP QUIT command on close. Need not
     wait for 221 response.
  */
  conn.send_data("QUIT\r\n");
}

void SMTP::set_header(string field, string value)
{
  /* We always hide the recipients list. We set it to
       "Undisclosed-recipients". Need to handle Cc and
       such stuff.
  */
  if(field == "To") {
    headers[field] = "Undisclosed-recipients";
  } else {
    headers[field] = value;
  }
}

string SMTP::mail_from(string mail_from)
{
  sender = mail_from;
  set_header("From",mail_from);
  set_header("Reply-To", mail_from);
  string mail_sender = "MAIL FROM: " + mail_from + "\r\n";
  conn.send_data(mail_sender);
  response = conn.recv_data();
  return response;
}

string SMTP::add_rcpt_to(string rcpt_to)
{
  if( rcpt_allowed ) {
    receivers.push_back(rcpt_to);
    string mail_rcvr = "RCPT TO: " + rcpt_to + "\r\n";
    conn.send_data(mail_rcvr);
    response = conn.recv_data();
  } else {
    response = "NO RCPT AFTER DATA\n";
  }
  return response;
}

string SMTP::end_mail()
{
  conn.send_data("\r\n.\r\n");
  response = conn.recv_data();
  return response;
}

string SMTP::helo()
{
  conn.send_data("HELO localhost\r\n");
  response = conn.recv_data();
  return response;
}
